package com.szh.gulimall.ware.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.szh.common.constant.GulimallCodeEnum;
import com.szh.common.exception.NoStockException;
import com.szh.gulimall.ware.vo.SkuHasStockVo;
import com.szh.gulimall.ware.vo.WareSkuLockVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import com.szh.gulimall.ware.entity.WareSkuEntity;
import com.szh.gulimall.ware.service.WareSkuService;
import com.szh.common.utils.PageUtils;
import com.szh.common.utils.R;

/**
 * 商品库存
 *
 * @author SongZiHao
 * @email 2656307671@qq.com
 * @date 2022-10-30 15:52:10
 */
@RefreshScope
@RestController
@RequestMapping("/ware/waresku")
public class WareSkuController {

    @Autowired
    private WareSkuService wareSkuService;

    /**
     * 锁定库存
     */
    @PostMapping("/lock/order")
    public R orderLockStock(@RequestBody WareSkuLockVo vo) {
        try {
            Boolean stock = wareSkuService.orderLockStock(vo);
            return R.ok().setData(stock);
        } catch (NoStockException ex) {
            return R.error(GulimallCodeEnum.NO_STOCK_EXCEPTION.getCode(), GulimallCodeEnum.NO_STOCK_EXCEPTION.getMsg());
        }
    }

    /**
     * 查询sku是否有库存
     */
    @PostMapping("/hasSkuStock")
    public R getHasSkuStock(@RequestBody List<Long> skuIds) {
        List<SkuHasStockVo> vos = wareSkuService.getHasSkuStock(skuIds);
        return R.ok().setData(vos);
    }

    /**
     * 条件查询商品库存列表
     */
    @GetMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = wareSkuService.queryPage(params);
        return R.ok().put("page", page);
    }

    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
		WareSkuEntity wareSku = wareSkuService.getById(id);
        return R.ok().put("wareSku", wareSku);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    public R save(@RequestBody WareSkuEntity wareSku) {
		wareSkuService.save(wareSku);
        return R.ok();
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    public R update(@RequestBody WareSkuEntity wareSku) {
		wareSkuService.updateById(wareSku);
        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    public R delete(@RequestBody Long[] ids) {
		wareSkuService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }
}
